const db = wx.cloud.database();
var app = getApp();
Page({
  data: {
    color: app.ext.color,
    product_list: [],
    height: 0
  },
  onLoad: function(options) {
    wx.getSystemInfo({
      success: (res) => {
        console.log(res.screenHeight);
        console.log(res.windowHeight);
        let h = res.windowHeight - 50;
        this.setData({
          height: h
        })
      }
    })
    this.getProducts();

  },
  onShow: function() {

    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.req == 1) {
      this._clear();
      this.getProducts();
      this.setData({
        req: 0
      })
    }
  },
  _clear() {
    this.setData({
      product_list: []
    })
  },
  getProducts() {
    let product_list = this.data.product_list;
    db.collection('index_diy').get().then(res => {
      console.log(res.data);
      const DATA = res.data;
      product_list = product_list.concat(DATA);
      this.setData({
        product_list: product_list
      });
    })

  },


  onAddProduct: function(e) {
    wx.navigateTo({
      url: `/pages/manage/xcx-add/index`
    });

  },
  onClickDel(e) {
    const that = this;
    db.collection('index_diy').doc(e.currentTarget.dataset.id).remove({
      success(res) {
        if (res.errMsg == "document.remove:ok") {
          that._clear();
          that.getProducts();
          wx.showToast({
            title: '数据已被删除',
          });
        } else {
          wx.showToast({
            title: '数据删除失败',
          });
        }

      },
      fail: console.error
    })
  },
  onClickUpt(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id)
    wx.navigateTo({
      url: `/pages/manage/template-add/index?id=` + e.currentTarget.dataset.id
    });
  },
  onClickDiy(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id);
    app.globalData.diyId = e.currentTarget.dataset.id;
    app.globalData.diyProduct = e.currentTarget.dataset.product;
    app.globalData.diyPageI = -1;
    app.globalData.diyEdit = "true";
    wx.navigateTo({
      url: `/pages/com/home/index`
    });
  },
  onClickMan(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id);
    app.globalData.diyId = e.currentTarget.dataset.id;
    app.globalData.diyProduct = e.currentTarget.dataset.product;
    wx.navigateTo({
      url: `/pages/manage/nav/index`
    });
  },
  onClickView(e) {
    wx.setStorageSync('diyId', e.currentTarget.dataset.id)
    app.globalData.diyId = e.currentTarget.dataset.id;
    app.globalData.diyProduct = e.currentTarget.dataset.product;
    app.globalData.diyPageI = -1;
    app.globalData.diyEdit = "false";
    if (e.currentTarget.dataset.product == 1) {
      wx.switchTab({
        url: `/pages/com/index/index`
      });
    } else {
      wx.navigateTo({
        url: `/pages/com/home/index`
      });
    }
  }
})